package tools;

import java.util.ArrayList;
import java.util.List;

public class Tools {

	/**
	 * 获取网页中<p class=""></p>的内容
	 * @return
	 */
	public static List<String> removeCommentLabel(String str){
		//最後的結果集
		List<String> result= new ArrayList<String>();
		while (true) {
			//获取p标签的开始下标
			int beginIndex = str.indexOf("<p class=\"\">")+12;
			//获取p标签的结束下标
			int endIndex=str.indexOf("</p>");
			//如果等于-1则结束循环
			if (beginIndex==11) break;
			//判断如果结束标签在开始标签之前 则过滤掉这个标签
			if (endIndex<beginIndex) {
				str=str.substring(endIndex+4);
				continue;
			}
			String out = str.substring(beginIndex, endIndex);
			str=str.substring(endIndex+4);
			result.add(wipe(out));
		}
		return result;
	}
	
	
	
	/**
	 * 去除html标签
	 * 
	 * @param tw
	 * @return
	 */
	public static String wipe(String tw) {
		String result = "";
		tw = tw.replace("&nbsp;", " ");
		while (true) {
			try {
				tw = tw.replace("  ", " ");
				int beginIndex = tw.indexOf("<");

				int endIndex = tw.indexOf(">") + 1;
				if (beginIndex == -1 || endIndex == 0)
					break;
				String substring = tw.substring(beginIndex, endIndex);
				tw = tw.replace(substring, "");

			} catch (Exception e) {
				// TODO: handle exception
			}

		}
		return tw;
	}

	/**
	 * 將每個評論分別存入list數組
	 * 
	 * @param str
	 * @return
	 */
	public static List<String> findComment(String str) {
		List<String> result = new ArrayList<String>();
		String temp = str;
		while (true) {
			int start = temp.indexOf("<div class=\"short-content\">");
			int end = temp.indexOf("</div>") + 6;
			if (end < start) {
				while (true) {
					end = temp.indexOf("</div>", end) + 6;
					if (end >= start) {
						break;
					}
				}

			}
			if (start == -1) {
				break;
			}
			str = temp.substring(start, end);
			temp = temp.substring(end);
			int beginNum = str.indexOf("toggle-") + 7;
			int endNum = str.indexOf("-copy");
			str = str.substring(beginNum, endNum);
			result.add(str);
		}
		return result;
	}
	
	/**
	 * 替换html字符实体
	 * @return
	 */
	public static String replaceHTMLChar(String in) {
		//html实体名称
				String[] value = {"&nbsp;","&lt;","&gt;","&amp;","&quot;","&apos;","&cent;","&pound;","&yen;","&euro;","&sect;","&copy;","&reg;","&trade;","&times;","&divide;"};
				//html实体显示
				String[] map= {" ","<",">","&","\"","'","￠","£","¥","€","§","©","®","™","×","÷"};
				
				for (int i = 0; i < value.length; i++) {
					in= in.replace(value[i], map[i]);
				}
		return in;
		
	}
	

}
